package org.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.captcha.model.CaptchaProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private static Logger loger= LoggerFactory.getLogger(CaptchaController.class);
    @Autowired
    private CaptchaProperties cp;
    private static long VALID_TIME_OUT=60*1000;
    @GetMapping("/getcaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cp.getWidth(), cp.getHeight());
        String code=lineCaptcha.getCode();
        session.setAttribute(cp.getSession().getKey(),code);
        session.setAttribute(cp.getSession().getDate(),new Date());
        System.out.println(lineCaptcha.getCode());
        loger.info("验证码："+code);
        try {
            lineCaptcha.write(response.getOutputStream());
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Pragma", "No-cache");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session){
        System.out.println(captcha);
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        String code = (String) session.getAttribute(cp.getSession().getKey());
        Date date = (Date) session.getAttribute(cp.getSession().getDate());
        if(date==null||(System.currentTimeMillis()-date.getTime()>VALID_TIME_OUT)){
            return false;
        }
        return captcha.equalsIgnoreCase(code);
    }
}
